package StudyCode.UI;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

/**
 * @author lixiaoyao
 * @date 2018/11/13 0013、下午 12:48
 * @description Action 示例代码
 */
public class ActionFrame extends JFrame {

	private JPanel buttonPanel;
	private static final int DEFAULT_WIDTH = 300;
	private static final int DEFAULT_HEIGHT = 200;

	public ActionFrame() {
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.buttonPanel = new JPanel();

		// define actions
		Action yellowAction = new ColorAction("Yellow", Color.YELLOW);
		Action blueAction = new ColorAction("Blue", Color.BLUE);
		Action redAction = new ColorAction("Red", Color.RED);

		// add buttons for the actions
		this.buttonPanel.add(new JButton(yellowAction));
		this.buttonPanel.add(new JButton(blueAction));
		this.buttonPanel.add(new JButton(redAction));

		// add panel to frame
		add(this.buttonPanel);

		// associate the Y,B and R keys with names
		InputMap inputMap = this.buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
		inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
		inputMap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
		inputMap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");

		// associate the names with actions
		ActionMap actionMap = this.buttonPanel.getActionMap();
		actionMap.put("panel.yellow", yellowAction);
		actionMap.put("panel.blue", blueAction);
		actionMap.put("panel.red", redAction);
	}

	public class ColorAction extends AbstractAction {

		public ColorAction(String name, Color color) {
			putValue(Action.NAME, name);
			putValue(Action.SHORT_DESCRIPTION, "Set panel color to" + name.toLowerCase());
			putValue("color", color);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			Color color = (Color) getValue("color");
			buttonPanel.setBackground(color);
		}
	}

	public static void main(String[] args) {
		JFrame frame = new ActionFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}
